#!/usr/bin/python
import autopy
import subprocess
import time
import logging
import os
import commands
from PIL import Image
import ConfigParser
import kmlParser

def google_earth(output_kml, img_file):
    print img_file
    status, dpi = commands.getstatusoutput('xrandr |grep "*"|awk \'{print $1}\'')
    cur_dir = os.getcwd()
    img_dir = '/'.join([cur_dir, 'results', 'imgs'])
    img = '/'.join([img_dir, img_file])
    a = subprocess.call(['xdg-open', output_kml])
    time.sleep(14)
    #autopy.key.tap(long(autopy.key.K_F11))
    if dpi == '1680x1050':
        #mac
        autopy.mouse.smooth_move(1637,285)
    elif dpi == '1920x1080':
        #dell
        autopy.mouse.smooth_move(1877,288)
    autopy.mouse.toggle(True)
    time.sleep(1)
    autopy.mouse.toggle(False)
    time.sleep(4)
    autopy.bitmap.capture_screen().save(img)
    time.sleep(3)
    autopy.mouse.smooth_move(32,352)
    time.sleep(1)
    autopy.mouse.click(autopy.mouse.RIGHT_BUTTON)
    autopy.mouse.smooth_move(165,410)
    time.sleep(1)
    autopy.mouse.click()
    if dpi == '1680x1050':
        #mac
        autopy.mouse.smooth_move(871,429)
    elif dpi == '1920x1080':
        #dell
        autopy.mouse.smooth_move(990,440)
    time.sleep(1)
    autopy.mouse.click()
    return img_file

def cut_image(image):
    cur = os.getcwd()
    image_base = cur + '/imgs/'
    imagefile = image_base + image
    box = (100, 110, 1500, 900)
    with Image.open(imagefile) as im:
        resized_image = im.crop(box)
        resized_image.save('/'.join([image_base, '_'.join(['resized',image.replace('png','jpg')])]))

# def usage():
#     print """
#     Usage: python %s -v <rdb-version> -t <kml type>
#     args:   -h: print help info
#             -v: rdb-version
#             -t: kml-type one of lane/avgps/paint/avslam/sign""" %(sys.argv[0])
#     sys.exit(1)


#main
logging.basicConfig(filename='./log/process.log', level=logging.INFO)
logger = logging.getLogger()
scope_file = './conf/scope.txt'
conf_ini = './conf/config.ini'
cf = ConfigParser.ConfigParser()
cf.read(scope_file)
cf2 = ConfigParser.ConfigParser()
cf2.read(conf_ini)

DO_SUPPORTED_POT = cf.sections()
DO_SUPPORTED_VER = cf2.get('general', 'support_ver').split(',')
DO_SUPPORTED_KML = cf2.get('general', 'support_type').split(',')

for version in DO_SUPPORTED_VER:
    for kmltype in DO_SUPPORTED_KML:
        for section in DO_SUPPORTED_POT:
            kmlinst = kmlParser.kmlBee(version, kmltype, section)
            kmlinst.get_scope()
            kmlinst.convert_scope()
            kmlinst.extract_elements()
            b = kmlinst.filter_elements()
            kmlinst.generate_kml()
            kmlfile = kmlinst.save_kml()
            logger.info("matched element count: " + str(len(b)) + '\t in outfile {}'.format(kmlfile))

kmlist = os.listdir('./results/out')
for kmlfile in kmlist:
    imgfile = kmlfile.strip('.kml') + '.jpeg'
    kmlpath = './results/out/' + kmlfile
    imgpath = './results/imgs/' + imgfile
    logger.info('generated images file : {}'.format(imgpath))
    image = google_earth(kmlpath, imgfile)
    cut_image(image)
    time.sleep(3)

